package com.example.administrator.myapplication;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.theartofdev.edmodo.cropper.CropImage;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    private Uri imageurl;
    private Uri resultUri;
    private String filename;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void takephoto(View v) throws IOException {
        File file = new File(getExternalCacheDir(), "image.jpg");
        if (file.exists()) {
            file.delete();
        }
        file.createNewFile();
        if (Build.VERSION.SDK_INT >= 24) {
            imageurl = FileProvider.getUriForFile(this, "com.example.administrator.myapplication", file);
        } else {
            imageurl = Uri.fromFile(file);
        }
        Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        i.putExtra(MediaStore.EXTRA_OUTPUT, imageurl);
        startActivityForResult(i, 101);


    }

    public void cutting(View v) {
        CropImage.activity(imageurl)
                .start(this);

    }

    public void upload(View v){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String s=resultUri.toString();
                    URI uri= null;
                    uri = new URI(s);
                    File file=new File(uri);
                    RequestBody body=RequestBody.create(MediaType.parse("image/png"),file);
                    MultipartBody.Builder builder=new MultipartBody.Builder();
                    builder.setType(MultipartBody.FORM);
                    builder.addFormDataPart("file","image.jpg",body);
                    MultipartBody multipartBody=builder.build();
                    Request request=new Request.Builder()
                            .post(multipartBody)
                            .url("http://10.1.66.232:8080/RestaurantServer/File/doUpload").build();
                    OkHttpClient client=new OkHttpClient();
                    Response response=client.newCall(request).execute();
                    String data = response.body().string();
                    JSONObject jsonObject = new JSONObject(data);
                    filename = jsonObject.getString("realfilename");


                } catch (URISyntaxException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void addfood(View v){
        Food food=new Food();
        food.setFoodname("矿泉水");
        food.setFoodprice(2);
        food.setFoodpic(filename);


        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("foodname",food.getFoodname());
            jsonObject.put("foodprice",food.getFoodprice());
            final String s = jsonObject.toString();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody=RequestBody.create(MediaType.parse("application/json"),s);
                    String url="http://10.1.66.232:8080/RestaurangServer/Food/addFood";
                    Request request=new Request.Builder()
                            .url(url)
                            .post(requestBody)
                            .build();
                    Response response= null;
                    try {
                        response = client.newCall(request).execute();
                        Log.e("s", response.body().string() );
                    } catch (IOException e) {
                        e.printStackTrace();
                    }


                }
            }).start();

        } catch (JSONException e) {
            e.printStackTrace();
        }


    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == 101) {
                try {
                    InputStream inputStream = getContentResolver().openInputStream(imageurl);
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    ImageView im = (ImageView) this.findViewById(R.id.photo);
                    im.setImageBitmap(bitmap);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }

        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            if (resultCode == RESULT_OK) {
                resultUri = result.getUri();

                try {
                    InputStream inputStream = getContentResolver().openInputStream(resultUri);
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    ImageView im = (ImageView) this.findViewById(R.id.photo);
                    im.setImageBitmap(bitmap);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
                Exception error = result.getError();
            }
        }
    }

}
